package com.fire.job.util;

import java.io.Serializable;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description: 一个表示一对数据的数据结构，用于存放成对的数据。
 * </p>
 */
@SuppressWarnings("serial")
public class Pair<T, V> implements Serializable, Cloneable {

	@SuppressWarnings("unchecked")
	public static <T, V> int binarySearchFirst(Pair<T, V>[] a, T key) {
		int low = 0;
		int high = a.length - 1;
		while (low <= high) {
			int mid = (low + high) >>> 1;
			Comparable<T> midVal = (Comparable<T>) (a[mid].first);
			int cmp = midVal.compareTo(key);
			if (cmp < 0)
				low = mid + 1;
			else if (cmp > 0)
				high = mid - 1;
			else
				return mid; // key found
		}
		return -(low + 1); // key not found.
	}

	private T first = null;

	private V second = null;

	public Pair() {
		super();
	}

	public Pair(T first, V second) {
		super();
		this.first = first;
		this.second = second;
	}

	/**
	 * 返回此Pair实例的浅表复制：并不克隆键和值本身。
	 */
	@Override
	public Object clone() {
		return new Pair<T, V>(first, second);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Pair) {
			@SuppressWarnings("rawtypes")
			Pair p = (Pair) obj;
			if (((this.getFirst() == null) && (p.getFirst() == null))
					|| ((this.getFirst() != null) && this.getFirst().equals(
							p.getFirst()))) {
				if (((this.getSecond() == null) && (p.getSecond() == null))
						|| ((this.getSecond() != null) && this.getSecond()
								.equals(p.getSecond()))) {
					return true;
				}
			}
		}
		return false;
	}

	public T getFirst() {
		return first;
	}

	public V getSecond() {
		return second;
	}

	public void setFirst(T first) {
		this.first = first;
	}

	public void setSecond(V second) {
		this.second = second;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("Pair[");
		sb.append("First: ").append(first.toString());
		sb.append(", Second: ").append(second.toString());
		sb.append("]");
		return sb.toString();
	}
}
